<?php

namespace app\admin\quick\actions;


use quick\admin\actions\RowAction;
use quick\admin\annotation\AdminAuth;
use quick\admin\components\Component;
use quick\admin\library\service\PluginService;
use quick\admin\library\service\QueueService;
use think\Request;

/**
 * 升级插件
 * @AdminAuth(title="升级插件",auth=true,menu=true,login=true)
 * @package app\admin\resource\example\actions
 */
class PluginUpdateAction extends RowAction
{

    /**
     * 模型主键
     *
     * @var string
     */
    public static $pk = "name";

    /**
     * 动作提交数据接口
     *
     * @return mixed
     * @throws \quick\admin\Exception
     * @throws \think\Exception
     */
    public function store()
    {
        $model = $this->findModel();
        if (!$model) {
            quick_abort(500, '资源不存在');
        }

        return $this->handle($model, $this->request);
    }


    /**
     * 关联模型
     *
     * @var string
     */
    protected static $model = 'app\common\model\SystemPlugin';


    protected function initAction()
    {
        $this->name = "升级";
        $this->display(Component::button($this->name())->type('text'));

        $this->confirm("升级前请做好数据备份",'确定升级吗？');

    }


    /**
     * @param $model
     * @param Request $request
     * @return \quick\admin\http\response\JsonResponse
     */
    public function handle($model, Request $request)
    {


        try {

            PluginService::instance()->upgrade($model->name,$request->get('version',''));
            $response = $this->response()->success()->message("升级成功".$request->get('version',''))
                ->event('admin_menu', [], 200, true);

        } catch (\Exception $exception) {
            $response = $this->response()->error($exception->getMessage());
        }
        return $response;
    }


}
